package com.qdlc.p2p.biz.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.qdlc.p2p.biz.service.UserVipLevelService;
import com.qdlc.p2p.common.exception.BusinessException;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.util.DateUtil;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dao.UserVipLevelDao;
import com.qdlc.p2p.dal.dto.UserVipLevel;

@Service
public class UserVipLevelServiceImpl implements UserVipLevelService {

	@Resource
	private UserVipLevelDao vipLevelDao;

	@Override
	public List<UserVipLevel> getAllLevel() {
		QueryParam param = QueryParam.getInstance().addParam("isDelete", false);
		return vipLevelDao.findByCriteria(param);
	}

	@Override
	public UserVipLevel findById(long id) {
		return vipLevelDao.find(id);
	}

	@Override
	public void save(UserVipLevel userVipLevel) {
		int maxLevel = vipLevelDao.getMaxLevel();
		userVipLevel.setAddTime(DateUtil.getNow());
		userVipLevel.setLevel(maxLevel + 1);
		vipLevelDao.save(userVipLevel);
	}

	@Override
	public void update(UserVipLevel userVipLevel) {
		vipLevelDao.update(userVipLevel);
	}

	@Override
	public void delete(UserVipLevel userVipLevel) {
		vipLevelDao.updateLevelByLevel(userVipLevel.getLevel());
		userVipLevel.setDelete(true);
		vipLevelDao.update(userVipLevel);
	}

	@Override
	public void update(double money, long redEnvelopeId, byte redEnvelopePayType) {
		int count = vipLevelDao.getCountByRedEnvelopeId(redEnvelopeId);
		if(count > 0){
			if(redEnvelopePayType != 1){
				throw new UserException("vip配置使用了此规则，发放方式只能为固定金额！", BusinessException.TYPE_JSON);
			}
			vipLevelDao.update(money, redEnvelopeId);
		}
	}
}
